<template>
	<view class="" style="width: 100vw;height: 100vh">
		<view class="" :style="{'background':kbackgroundColor2}" style="min-height: 100vh">
			<hx-navbar title="企业认证" :back="true" :fixed="false" :color="knavTitleColor" barPlaceholder="hidden"
				transparent="auto">
			</hx-navbar>
			<view class="container"
				:class="[{'container-black':ktheme =='black'},{'container-purple':ktheme =='purple'}]">
				<view class="content" :style="{'color':knormalColor}">
					<view class="item item-border">
						<text class="title">企业名称</text>
						<input class="input-view" v-model="entName" placeholder="请输入企业名称" />
					</view>
					<view class="item item-border">
						<text class="title">社会统一代码</text>
						<input class="input-view" v-model='entUniscid' placeholder="请输入社会统一代码" />
					</view>
					<view class="item item-border">
						<text class="title">营业执照</text>
						<view class="photo-view">
							<view class="photo-item" @click="uploadImage">
								<image v-if="licenseImage==''" src="@/static/user/wallet/auth-photo-add.png"></image>
								<image v-else :src="licenseImage" mode="aspectFit"></image>
							</view>
						</view>
					</view>
					<view class="item item-border">
						<text class="title">法人姓名</text>
						<input class="input-view" v-model='frName' placeholder="请输入法人姓名" />
					</view>
					<view class="item item-border">
						<text class="title">法人身份证</text>
						<input class="input-view" v-model="frIdnumber" placeholder="请输入法人身份证" />
						<!-- 	<view class="photo-view">	<view class="photo-item" style="margin-right: 20rpx;" @click="uploadImage(1)">
							<image v-if="photoImageInfo.idImage1" :src="photoImageInfo.idImage1" mode="aspectFit"></image>
							<image v-if="!photoImageInfo.idImage1" src="@/static/user/wallet/auth-photo-add.png"></image>
						</view> -->
						<!-- 	<view class="photo-item" @click="uploadImage(2)">
							<image v-if="photoImageInfo.idImage2" :src="photoImageInfo.idImage2" mode="aspectFit"></image>
							<image v-if="!photoImageInfo.idImage2" src="@/static/user/wallet/auth-photo-add.png"></image>
						</view></view> -->

					</view>

					<view class="item item-border">
						<text class="title">开户银行账户</text>
						<input class="input-view" v-model='cardNumber' placeholder="请输入开户银行账户" />
					</view>
					<view class="item item-border">
						<text class="title">开户银行</text>
						<input class="input-view" v-model='bankName' placeholder="请输入开户银行" />
					</view>
					<view class="item item-border-none">
						<text class="title">联系人手机号</text>
						<input class="input-view" v-model='phone' placeholder="请输入联系人手机号" />
					</view>
				</view>
			</view>
			<view class="bottom_box">
				<!-- //false新增   ture修改 -->
				<view class="submit_btn" v-if="!ifVerify" :style="{'background':kbuttonBgColor}" @click="submit()"> 提交
				</view>
				<view class="submit_btn" v-if="ifVerify" :style="{'background':kbuttonBgColor}" @click="update()"> 提交
				</view>
			</view>
			<!-- 购买 提醒 -->
			<uni-popup ref="tipsPopup" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'">
				<view class="store-view store-border-all tips-padding"
					:style="{'background':kbackgroundColor,color:knormalColor}"
					:class="[{'alert-border-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
					<text class="popup-title">提交成功</text>
					<text class="popup-subtitle">
						您的企业账户信息已提交，
						预计1-2个工作日内完成审核。
					</text>
				</view>
			</uni-popup>
			<!-- 购买 提醒 -->
			<uni-popup ref="ticfPopup" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'">
				<view class="store-view store-border-all tips-padding"
					:style="{'background':kbackgroundColor,color:knormalColor}"
					:class="[{'alert-border-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
					<text class="popup-title">提交</text>
					<text class="popup-subtitle">
						该企业已提出申请，请勿重复申请
					</text>
				</view>
			</uni-popup>
		</view>
	</view>
</template>
<script>
	import {
		apiBaseUrl
	} from '@/config/config.js';
	export default {
		data() {
			return {
				licenseImage: '',
				phone: "",
				cardNumber: "",
				bankName: "",
				frIdnumber: "",
				frName: '',
				entUniscid: "",
				entName: "",
				id:"",
				photoType: 0,
				ifVerify: false, //false新增   ture修改
				data: {},
				photoImageInfo: {
					businessLicense: '',
					idImage1: '',
					idImage2: '',
					account: {},

				}
			}
		},
		onLoad() {
			this.userAccount()
			this.getPurseEnte()
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		methods: {
			//验证获取企业
			getPurseEnte() {
				this.$api.getPurseEnte(res => {
					if (res.status) {
						if(res.data.data==null || res.data.data =='' ){
								this.ifVerify = false
						}else{
							this.ifVerify = true
							this.licenseImage = res.data.data.licenseImage
							this.phone = res.data.data.phone
							this.cardNumber = res.data.data.cardNumber
							this.bankName = res.data.data.bankName
							this.frIdnumber = res.data.data.frIdnumber
							this.frName = res.data.data.frName
							this.entUniscid = res.data.data.entUniscid
							this.entName = res.data.data.entName
							this.id = res.data.data.id
							console.log("1---", this.entName);
						}
					} else {
						this.$common.errorToShow(res.message)
					}
					console.log("	this.ifVerify--", this.ifVerify);

				})
			},
			userAccount() {
				this.$api.userAccount({}, res => {
					if (res.status) {
						this.account = res.data
					} else {
						this.$common.errorToShow(res.message)
					}
				})
			},
			yz() {
			
		},
		submit() {
	 if (this.entName == '') {
	 	this.$common.errorToShow('请输入企业名称')
	 	return false
	 } else if (this.entUniscid == '') {
	 	this.$common.errorToShow('请输入社会统一代码')
	 } else if (this.licenseImage == '') {
	 	this.$common.errorToShow('请提交营业执照')
	 } else if (this.frIdnumber == '') {
	 	this.$common.errorToShow('请输入法人身份证')
	 } else if (this.frName == '') {
	 	this.$common.errorToShow('请输入法人姓名')
	 } else if (!this.validentity(this.frIdnumber)) {
	 	this.$common.errorToShow('身份证信息填写不正确')
	 } else if (this.bankName == '') {
	 	this.$common.errorToShow('请输入开户银行账户')
	 } else if (this.cardNumber == '') {
	 	this.$common.errorToShow('请输入开户银行')
	 } else if (this.phone == '') {
	 	this.$common.errorToShow('请输入联系人手机号')
	 } else if (!this.validateMobile(this.phone)) {
	 	this.$common.errorToShow('手机号格式不正确');
	 }else{
	 
			var data = {
				licenseImage: this.licenseImage,
				phone: this.phone,
				cardNumber: this.cardNumber,
				bankName: this.bankName,
				frIdnumber: this.frIdnumber,
				entUniscid: this.entUniscid,
				entName: this.entName,
				uid: this.account.uid,
				frName: this.frName,
				
			}
			this.$api.addPurseEnt(data, res => {
				if (res.status) {
					if (res.data == '该企业已提出申请，请勿重复申请') {
						this.$refs.ticfPopup.open()
					} else {
						this.$refs.tipsPopup.open()
					}
					setTimeout(function() {
						uni.redirectTo({
							url: '/pages/user/wallet_system/wallet_system'
						})
					}, 3000)
				} else {
					this.$common.errorToShow(res.message)
				}
			})

}
		},
		update() {
			if (this.entName == '') {
							this.$common.errorToShow('请输入企业名称')
							return false
						} else if (this.entUniscid == '') {
							this.$common.errorToShow('请输入社会统一代码')
						} else if (this.licenseImage == '') {
							this.$common.errorToShow('请提交营业执照')
						} else if (this.frIdnumber == '') {
							this.$common.errorToShow('请输入法人身份证')
						} else if (this.frName == '') {
							this.$common.errorToShow('请输入法人姓名')
						} else if (this.bankName == '') {
							this.$common.errorToShow('请输入开户银行账户')
						} else if (this.cardNumber == '') {
							this.$common.errorToShow('请输入开户银行')
						} else if (this.phone == '') {
							this.$common.errorToShow('请输入联系人手机号')
						} else if (!this.validateMobile(this.phone)) {
							this.$common.errorToShow('手机号格式不正确');
						}else{

			var data = {
				licenseImage: this.licenseImage,
				phone: this.phone,
				cardNumber: this.cardNumber,
				bankName: this.bankName,
				frIdnumber: this.frIdnumber,
				entUniscid: this.entUniscid,
				entName: this.entName,
				uid: this.account.uid,
				frName: this.frName,
				id:this.id,
				status:1
			}
			this.$api.updatePurseEntDetail(data, res => {
				if (res.status) {
					this.$refs.tipsPopup.open()
					setTimeout(function() {
						uni.redirectTo({
							url: '/pages/user/wallet_system/wallet_system'
						})
					}, 3000)
				} else {
					this.$common.errorToShow(res.message)
				}
			})
			}
		},
		//手机号验证
		validateMobile(phone) {
			const re = /^1(3|4|5|7|8|9|6)\d{9}$/
			return re.test(phone);
		},
		//身份验证
		validentity(identity) {
			var sf = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/
			return sf.test(identity);
		},
		valname(name) {
			var nm = /^[A-Za-z\s.-]+$/
			return nm.test(name);
		},
		// upload(filePath) {
		// 	var _this = this
		// 	uni.chooseImage({
		// 		count: 1, // 默认9  
		// 		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
		// 		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
		// 		success: function(res) {
		// 			const tempFilePaths = res.tempFilePaths;
		// 			_this.recursionCompressH5(tempFilePaths[0]); // 假设只选择了一张图片 
		// 		}
		// 	});
		// },
		uploadImage() {
			let _this = this
			// this.photoType = type
			uni.chooseImage({
				success: (chooseImageRes) => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					let filePath = tempFilePaths[0]
					//#ifdef APP-IOS || APP-ANDROID
					const theme = uni.getStorageSync('theme');
					let color = theme == 'purple' ? "#000000" : "#ffffff"
					let style = theme == 'purple' ? "black" : "white"
					var styles = {
						color: color,
						background: "rgba(0,0,0,0.0)",
						style: style,
					}
					var waiting = plus.nativeUI.showWaiting("上传中...", styles);
					_this.uploadFile(filePath)
					//#endif
					// #ifndef APP-IOS || APP-ANDROID
					uni.showLoading({
						title: '上传中...'
					});
					_this.afterRead(tempFilePaths)
					// #endif
				}
			});
		},
		uploadFile(filePath) {
			var _this = this
			var url = apiBaseUrl + 'purse/purseExtractTopup/saveTopup?' + this.licenseImage
			let token = this.$db.get('userToken')
			uni.uploadFile({
				url: url, // 仅为示例，并非真实的接口地址  
				filePath: filePath,
				fileType: 'image',
				name: 'file',
				header: {
					'Authorization': 'Bearer ' + token
				},
				success: (res) => {
					// console.log("uploadFileRes00", JSON.parse(res.data));
					let data = JSON.parse(res.data);
					_this.licenseImage = data.data.data;
					//#ifdef APP-PLUS
					plus.nativeUI.closeWaiting();
					//#endif
					uni.hideLoading();
				},
				fail: (error) => {
					_this.$common.errorToShow(error)
					//#ifdef APP-PLUS
					plus.nativeUI.closeWaiting();
					//#endif
					uni.hideLoading();
				},
				complete: () => {
					//#ifdef APP-PLUS
					plus.nativeUI.closeWaiting();
					//#endif
					uni.hideLoading();
				}
			});
		},
		//压缩
		recursionCompressH5(url) {
			return new Promise((resolve, reject) => {
				this.recursionCompress(url, resolve)
			})
		},
		// 传入blob路径，.then()获取blob文件
		httpRequest(src) {
			let that = this
			return new Promise((resolve, reject) => {
				let xhr = new XMLHttpRequest()
				xhr.open('GET', src, true)
				xhr.responseType = 'blob'
				xhr.onload = function(e) {
					if (this.status == 200) {
						let myBlob = this.response
						let files = new window.File(
							[myBlob],
							myBlob.type, {
								type: myBlob.type
							}
						) // myBlob.type 自定义文件名
						resolve(files)
					} else {
						reject(false)
					}
				}
				xhr.send()
			})
		},
		recursionCompress(url, resolve) {
			let _this = this
			uni.getImageInfo({
				src: url,
				success(res) {
					let canvasWidth = res.width; //图片原始长宽
					let canvasHeight = res.height;
					let img = new Image();
					img.src = res.path;
					let canvas = document.createElement("canvas");
					let ctx = canvas.getContext("2d");
					canvas.width = canvasWidth / 2;
					canvas.height = canvasHeight / 2;
					ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
					canvas.toBlob(function(fileSrc) {
						let imgSrc = window.URL.createObjectURL(fileSrc);
						uni.getFileInfo({
							filePath: imgSrc,
							success: (resFileInfo) => {
								console.log(imgSrc, 'resFileInfo', resFileInfo)
								if (resFileInfo.size > 1024 * 1024) {
									//压缩后大于1M就继续压缩
									console.log('再次压缩')
									_this.recursionCompress(imgSrc, resolve);
									// indexObj.recursionCompressH5(imgSrc, callback, item);
									return;
								} else {
									resolve(imgSrc)
								}
							},
						});
					});
				}
			});
		},
		afterRead(e) {
			let _this = this
			const file = e
			console.log("e", e)
			// 遍历图片资源
			file.map(item => {
				console.log(item, 'item')
				// 进行压缩图片
				this.recursionCompressH5(item).then(url => {
					console.log(url, 'url')
					_this.httpRequest(url).then(res => {
						console.log(res, '成功转换为blob文件');
						const fileReader = new FileReader()
						fileReader.readAsDataURL(
							res
						) // 读取blob类型的图像文件（不是blob路径），读取成功触发onload方法，并得到result（base64格式的图片）
						fileReader.onload = (event) => {
							console.log(fileReader.result, 'fileReader.result - base64格式');
							if (fileReader.result) {
								// 上传最终压缩之后的图片
								_this.uploadFile(fileReader.result).then(res => {
									console.log(res)
									// this.fileList.push(res)
								}).catch(() => {
									//#ifdef APP-PLUS
									plus.nativeUI.closeWaiting();
									//#endif
									uni.hideLoading();
								})
								// 调用wx_uploadImage接口，图片大小必须是1M以下，否则报错
								// wx_uploadImage({
								//   image: fileReader.result
								// }).then(res => {
								//   console.log('上传图片成功', res)
								//   this.image = res.storage_path
								// })
							}
						}
					})
				})
			})
		},
		}
	}
</script>

<style lang="scss" scoped>
	.body {
		width: 100vw;
		height: 100vh;
	}

	.container {
		margin: 40rpx 40rpx 0 40rpx;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;

		.content {
			// margin-top: 40rpx;
			// margin-bottom: 40rpx;
			display: flex;
			flex-direction: column;

			// padding: 0 40rpx;
			.item-border {
				border-bottom: 2rpx solid #535353;
			}

			.item-border-none {
				border-bottom: 0rpx solid #535353;
			}

			.item {
				display: flex;
				flex-direction: row;
				align-items: center;
				margin: 0 28rpx;
				padding: 28rpx 0;

				font-size: 26rpx;

				.title {
					// margin-top: 10rpx;
				}

				.input-view {
					margin-left: auto;
					text-align: right;
					// border: 2rpx solid #535353;
					width: 60%;
					height: 60rpx;
					border-radius: 10rpx;
				}

				.photo-view {
					margin-left: auto;
					display: flex;
					flex-direction: row;
					align-items: center;

					.photo-item {
						width: 80rpx;
						height: 80rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

				}
			}
		}
	}

	.bottom_box {
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		bottom: 100rpx;
		width: 100%;

		.submit_btn {
			width: 280rpx;
			height: 88rpx;
			line-height: 88rpx;
			color: white;
			text-align: center;
			border-radius: 50rpx;
		}

		.submit_btn2 {
			width: 280rpx;
			height: 88rpx;
			border: 1rpx solid #d9d9d9;
			color: #999;
			line-height: 88rpx;
			text-align: center;
			border-radius: 50rpx;
		}
	}

	.container-purple {
		background-color: #ffffff;
	}

	.container-black {
		background-color: #1B1B1B;
	}
</style>